import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JPanel;
import javax.swing.Timer;

import poset.Item;
import poset.PosetSpace;

import spaces.Node;


@SuppressWarnings("serial")
public class PosetSpaceViewer extends JPanel {
	
	private static final int NODE_RAD = 5;
	private PosetSpace posetSpace;
	Timer timer;
	
	private int iters = 0;
	private double tension = 0;
	private double tensionGrowth = 1;
	private double avgTension = 0;

	public PosetSpaceViewer(PosetSpace ps){
		this.posetSpace = ps;
		posetSpace.initialize();
		setBackground(Color.BLACK);
		
		timer = new Timer(0, new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e) {
				posetSpace.next();
				iters++;
				tensionGrowth = 10.0/(10+iters);
				tension = posetSpace.getTension();
				avgTension = tension*tensionGrowth + avgTension*(1-tensionGrowth);
				repaint();
			}
		});
	}
	
	public void start(){
		timer.start();
	}
	
	public void paint(Graphics g){
		super.paint(g);
		if(posetSpace.getDims() == 2){
			double minX = posetSpace.getMin(0);
			double maxX = posetSpace.getMax(0);
			double minY = posetSpace.getMin(1);
			double maxY = posetSpace.getMax(1);
			double rangeX = maxX - minX;
			double rangeY = maxY - minY;
			double xRatio = rangeX/getWidth();
			double yRatio = rangeY/getHeight();
			double maxRatio = Math.max(xRatio,yRatio);

			// Draw Nodes
			for(Node node : posetSpace.getNodeSpace().getNodes()){
				if(node instanceof Item){
					g.setColor(Color.RED);
				} else {
					g.setColor(Color.GREEN);
				}
				g.fillOval( (int)(-(rangeX/maxRatio)/2+getWidth()/2 + (node.getPos().getValue(0)-minX)/maxRatio)-NODE_RAD, 
							(int)(-(rangeY/maxRatio)/2+getHeight()/2 + (node.getPos().getValue(1)-minY)/maxRatio)-NODE_RAD, NODE_RAD*2, NODE_RAD*2);
				/*
				g.drawString( node.getName(),
							  (int)(-(rangeX/maxRatio)/2+getWidth()/2 + (node.getPos().getValue(0)-minX)/maxRatio)-NODE_RAD, 
							  (int)(-(rangeY/maxRatio)/2+getHeight()/2 + (node.getPos().getValue(1)-minY)/maxRatio)-NODE_RAD);
							  */
			}
			
		}
		g.setColor(Color.YELLOW);
		g.drawString( "Tension: "+posetSpace.getTension(), 5, getHeight()-5 );
	}
}
